import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Table, Popconfirm, message, Modal } from 'antd';
import { DeleteOutlined, PlusOutlined, EditOutlined } from '@ant-design/icons';
import { getObject, toast, requestBody, apis, deleteObject } from "@/service/common";

export interface ApiGroup {
    id?: string;
    name: string | null;
}

interface ApiGroupModelProps {
    visible: boolean;
    onCancel: () => void;
}

const ApiGroupModel: React.FC<ApiGroupModelProps> = ({
    visible,
    onCancel
}) => {
    const [form] = Form.useForm();
    const [data, setData] = useState<ApiGroup[]>([]);
    const [editingKey, setEditingKey] = useState('');
    const [loading, setLoading] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const [currentItem, setCurrentItem] = useState<ApiGroup | null>(null);

    const getList = () => {
        getObject({ url: apis.apiServer.groupList }).then(({ data }) => {

            setData(data || []);
        })
    }

    useEffect(() => {
        if (visible) {
            getList()
        }
    }, [visible]);

    const isEditing = (record: ApiGroup) => record.id === editingKey;

    const handleAdd = () => {
        const newRecord: ApiGroup = {
            id: `new_${Date.now()}`,
            name: null
        };
        setData([newRecord, ...data]);
        setEditingKey(newRecord.id);
        form.setFieldsValue({ name: '' });
    };

    const handleEdit = (record: ApiGroup) => {
        form.setFieldsValue({ name: record.name || '' });
        setEditingKey(record.id || '');
    };

    const handleCancelEdit = async () => {
        await form.validateFields();
        setEditingKey('');

    };

    const handleSave = async (id: any) => {
        try {
            if (String(id).startsWith("new_")) {
                id = null
            }
            const values = await form.validateFields();
            requestBody({ url: apis.apiServer.groupSave, data: { id, ...values } }).then(() => {
                toast.success('保存成功');
                setEditingKey('');
                getList();
            })
        } catch (errInfo) {
            console.log('验证失败:', errInfo);
        }
    };

    const handleDelete = async (id: any) => {
        try {
            deleteObject({ url: apis.apiServer.groupDelete, data: [id] }).then(res => {
                toast.success('删除成功');
                getList();
            })

        } catch (error) {
            toast.error('删除失败');
        }
    };

    const columns = [
        {
            title: '分组名称',
            dataIndex: 'name',
            key: 'name',
            render: (text: string | null) => text || '-',
            editable: true,
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (_: any, record: ApiGroup) => {
                const editable = isEditing(record);
                return editable ? (
                    <span>
                        <Button
                            type="link"
                            onClick={() => record.id && handleSave(record.id)}
                            style={{ marginRight: 8 }}
                        >
                            保存
                        </Button>
                        <Button type="link" onClick={handleCancelEdit}>
                            取消
                        </Button>
                    </span>
                ) : (
                    <>
                        <Button
                            type="link"
                            disabled={editingKey !== ''}
                            onClick={() => handleEdit(record)}
                            icon={<EditOutlined />}
                        >
                            编辑
                        </Button>
                        <Button
                            color="gold" variant="link"
                            disabled={editingKey !== ''}
                            onClick={() => {
                                setCurrentItem(record);
                                setModalVisible(true);
                            }}
                        >
                            详情
                        </Button>
                        <Popconfirm
                            title="确定删除吗?"
                            onConfirm={() => record.id && handleDelete(record.id)}
                        >
                            <Button type="link" danger icon={<DeleteOutlined />}>
                                删除
                            </Button>
                        </Popconfirm>
                    </>
                );
            },
        },
    ];

    const mergedColumns = columns.map(col => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record: ApiGroup) => ({
                record,
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });

    const EditableCell = ({
        editing,
        dataIndex,
        title,
        children,
        ...restProps
    }: any) => {
        return (
            <td {...restProps}>
                {editing ? (
                    <Form.Item
                        name={dataIndex}
                        style={{ margin: 0 }}
                        rules={[
                            {
                                required: true,
                                message: `请输入${title}!`,
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                ) : (
                    children
                )}
            </td>
        );
    };

    return (
        <Modal
            title="API分组管理"
            visible={visible}
            onCancel={onCancel}
            footer={null}
            width={800}
            destroyOnClose
            maskClosable={false}
        >
            <div style={{ marginBottom: 16 }}>
                <Button
                    type="primary"
                    onClick={handleAdd}
                    icon={<PlusOutlined />}
                    disabled={editingKey !== ''}
                >
                    添加分组
                </Button>
            </div>

            <Form form={form} component={false}>
                <Table
                    components={{
                        body: {
                            cell: EditableCell,
                        },
                    }}
                    bordered
                    dataSource={data}
                    columns={mergedColumns}
                    rowKey="id"
                    pagination={false}
                    loading={loading}
                    onRow={record => ({
                        onClick: () => { },
                    })}
                />
            </Form>

            <Modal
                title="分组详情"
                visible={modalVisible}
                onCancel={() => setModalVisible(false)}
                footer={null}
            >
                {currentItem && (
                    <div>
                        <p><strong>id:</strong> {currentItem.id}</p>
                        <p><strong>名称:</strong> {currentItem.name || '-'}</p>
                    </div>
                )}
            </Modal>
        </Modal>
    );
};

export default ApiGroupModel;
